<template>
  <div class="szLogin sz-login__reset">
    <div class="header">重置密码</div>
    <div class="content">
      <el-form ref="resetFormRef" :model="resetForm" :rules="resetRules">
        <template v-if="resetByPhone">
          <el-form-item prop="phone" class="phoneInput">
            <el-input
              name="phone"
              v-model="resetForm.phone"
              placeholder="请输入手机号"
            >
              <template slot="prefix">+86</template>
            </el-input>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item prop="email">
            <el-input v-model="resetForm.email" placeholder="请输入邮箱" />
          </el-form-item>
        </template>
        <el-form-item prop="password" class="password">
          <el-input
            type="password"
            v-model="resetForm.password"
            placeholder="设置新密码"
            show-password
          />
          <div class="passwordRule">
            * 8-16位，须包含至少3种字符（数字、大写字母、小写字母或特殊符号）
          </div>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            type="password"
            v-model="resetForm.confirmPassword"
            placeholder="确认新密码"
            show-password
          />
        </el-form-item>
        <el-form-item prop="captcha" class="captchaGroup">
          <el-input
            name="captcha"
            v-model="resetForm.captcha"
            placeholder="请输入验证码"
          >
          </el-input>
          <el-button
            class="captchaButton"
            :class="hasSendSms && 'countdown'"
            :disabled="hasSendSms"
            @click="handleGetImgCaptcha"
            >{{
              hasSendSms ? `重新获取(${countdown})` : "获取验证码"
            }}</el-button
          >
        </el-form-item>
      </el-form>
      <div class="footer">
        <el-button class="confirmButton" type="primary" @click="handleSubmit"
          >确定</el-button
        >
      </div>
      <div class="footer">
        <el-button class="change" type="text" @click="handleChangeResetType">
          通过{{ resetByPhone ? "邮箱" : "手机号" }}重置密码
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {
  sendResetSms,
  sendResetEmail,
  saveResetInfo,
  checkCaptchaByPhone,
  checkCaptchaByEmail
} from "@/apis/login";
import { checkPhoneNumber, checkPassword } from "@/utils/validator";
let countdownId = null;
export default {
  name: "ResetPassword",
  props: {
    imgCaptchaInfo: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    const checkConfirmPassword = (rule, value, callback) => {
      // checkPassword(rule, value, callback);
      if (value !== this.resetForm.password) {
        return callback(new Error("两次输入密码不一致!"));
      }
      callback();
    };
    return {
      resetByPhone: false,
      resetForm: {
        phone: "",
        email: "",
        password: "",
        confirmPassword: "",
        captcha: ""
      },
      resetRules: {
        phone: [
          { required: true, validator: checkPhoneNumber, trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        password: [
          { required: true, validator: checkPassword, trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, validator: checkConfirmPassword, trigger: "blur" }
        ],
        captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }]
      },
      hasSendSms: false,
      countdown: 60
    };
  },
  watch: {
    imgCaptchaInfo(newVal, oldVal) {
      if (newVal && newVal.captcha && (newVal.captcha !== oldVal.captcha)) {
        this.handleCheckImgCaptcha(newVal);
      }
    }
  },
  methods: {
    handleChangeResetType() {
      this.resetByPhone = !this.resetByPhone;
      this.$refs["resetFormRef"].clearValidate();
      this.$refs["resetFormRef"].resetFields();
    },
    handleGetImgCaptcha() {
      this.$refs["resetFormRef"].validateField(
        this.resetByPhone ? "phone" : "email",
        (error) => {
          if (!error) {
            this.$emit("openDialog");
          }
        }
      );
    },
    // 根据图片验证码发送短信
    async handleCheckImgCaptcha({ captcha, verifyKey }) {
      try {
        const params = {
          captcha,
          verKey: verifyKey,
          type: 1
        };
        Object.assign(
          params,
          this.resetByPhone
            ? { regionCode: "86", cellphone: this.resetForm.phone }
            : { lang: "zh-CN", mail: this.resetForm.email }
        );
        const res = this.resetByPhone
          ? await sendResetSms(params, { customApi: this.$attrs.customApi })
          : await sendResetEmail(params, { customApi: this.$attrs.customApi });
        if (res.status === 1) {
          this.$message.success("验证码已发送");
          this.$emit("closeDialog");

          // 禁用获取验证码按钮
          this.hasSendSms = true;
          countdownId = setInterval(() => {
            if (this.countdown > 0) {
              this.countdown -= 1;
            } else {
              clearInterval(countdownId);
              this.hasSendSms = false;
              this.countdown = 60;
            }
          }, 1000);
        } else {
          this.$emit("closeDialog");
          this.$message({ type: 'error', message: res.message });
        }
      } catch (err) {
        console.error(err);
      }
    },
    handleSubmit() {
      this.$refs["resetFormRef"].validate((valid) => {
        if (valid) {
          this.resetByPhone ? this.checkPhoneCaptcha() : this.checkEmailCaptcha();
        }
      });
    },
    // 检查手机验证码
    async checkPhoneCaptcha() {
      try {
        const params = {
          areaCode: "86",
          cellphone: this.resetForm.phone,
          code: this.resetForm.captcha
        }
        const res = await checkCaptchaByPhone(params, { customApi: this.$attrs.customApi });
        if (res.status === 1) {
          this.handleReset();
        } else {
          this.$message({ type: 'error', message: res.message });
        }
      } catch (err) {
        console.error(err);
      }
    },
    // 检查邮箱验证码
    async checkEmailCaptcha() {
      try {
        const params = {
          mail: this.resetForm.email,
          code: this.resetForm.captcha
        }
        const res = await checkCaptchaByEmail(params, { customApi: this.$attrs.customApi });
        if (res.status === 1) {
          this.handleReset();
        } else {
          this.$message({ type: 'error', message: res.message });
        }
      } catch (err) {
        console.error(err);
      }
    },
    // 重置密码
    async handleReset() {
      try {
        const { password, captcha, phone, email } = this.resetForm;
        const params = {
          password,
          code: captcha,
          type: this.resetByPhone ? 1 : 2,
          loginName: this.resetByPhone ? phone : email
        }
        const res = await saveResetInfo(params, { customApi: this.$attrs.customApi });
        if (res.status === 1) {
          this.$message.success('修改成功！');
          this.$refs["resetFormRef"].resetFields();
          this.$emit("resetSuccess", res, this.resetForm);
        } else {
          this.$emit("resetFailed", res, this.resetForm);
          this.$message({ type: 'error', message: res.message });
        }
      } catch (err) {
        console.error(err);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
@import url("/styles/login.scss");
.sz-login__reset {
  .header {
    color: #303133;
    text-align: center;
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 30px;
  }
  .content {
    .password {
      position: relative;
    }
    .passwordRule {
      font-weight: 400;
      font-size: 10px;
      line-height: 12px;
      color: #c0c4cc;
    }
  }
  .footer {
    text-align: center;
    .confirmButton {
      width: 100%;
      margin-top: 10px;
      height: 44px;
    }
    .change {
      padding: 0;
      line-height: 12px;
      margin-top: 15px;
    }
  }
}
</style>
